package com.qf.vote.controller;

import com.qf.vote.service.VoteService;
import com.qf.vote.vo.R;
import com.qf.vote.vo.VoteEchartVo;
import com.qf.vote.vo.VoteVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/vote")
@Slf4j
public class VoteController {

    @Autowired
    VoteService voteService;

    @GetMapping("/votelist")
    public R votelist(){
        VoteEchartVo voteEchartVo =  voteService.voteListForEchart();
        return R.ok(voteEchartVo);
    }

    /**
     * 获取所有获选人的得票信息
     * @return
     */
    @GetMapping("/getall")
    public R getAllVote(){
        log.info("getAllVote被调用了");
        List<VoteVo> data = voteService.getAllVote();
        return R.ok(data);
    }

    /**
     * 投票接口
     * @param phone 发起投票的手机号
     * @param name 候选人的名字
     * @return
     */
    @GetMapping("/dovote/{phone}/{name}")
    public R doVote(@PathVariable("phone") String phone,@PathVariable("name") String name) throws Exception {
        log.info("入参为:phone={},name={}",phone,name);

        // 检查参数是否为空，如果为空则直接抛出异常
        if (phone==null || phone.equals("")){
            throw new Exception("手机号为空!");
        }

        if (name==null || name.equals("")){
            throw new Exception("候选人名字为空!");
        }

        // 调用service对象进行具体的投票业务逻辑处理
        HashMap<String, Object> data = voteService.doVote(phone, name);

        // 返回结果
        return R.ok(data);
    }
}
